package service

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils/storage"
	"github.com/kataras/golog"
	"strconv"
)

type User struct {}

func (service *User) Insert(vo *model.AcceptUserVO) error {
	return service.createOrUpdate(vo, true)
}

// 更改用户表,角色表
func (service *User) createOrUpdate(vo *model.AcceptUserVO, isCreate bool) error {
	var (
		err error
		tx = storage.MySqlDb().Begin()
		uid = strconv.FormatUint(uint64(vo.AdminUser.ID), 10)
		//buffer bytes.Buffer
		//sql = "insert into `casbin_rule` (`p_type`,`v0`,`v1`,`v2`,`v4`,`v5`) values"
	)

	// 用户表
	if isCreate {
		if err = tx.Create(&vo.AdminUser).Error; err != nil {
			goto ERR
		}
		uid = strconv.FormatUint(uint64(vo.AdminUser.ID), 10)
	} else {
		if err = tx.Model(&model.User{}).Save(&vo.AdminUser).Error; err != nil {
			goto ERR
		}
	}

	// 角色表
	// 需要删除的
	if vo.DeleteRids != nil && len(vo.DeleteRids) > 0 {
		if err = tx.Delete(&model.CasbinRule{}, "id in (?)", vo.DeleteRids).Error; err != nil {
			goto ERR
		}
	}

	// 需要添加的
	if vo.AddRoles != nil && len(vo.AddRoles) > 0 {
		for _, v := range vo.AddRoles {
			v.V0 = uid
			if err = tx.Create(&v).Error; err != nil {
				golog.Errorf("新建用户时，添加角色信息失败。错误：%s", err)
				goto ERR
			}
		}
	}

	tx.Commit()
	return nil
ERR:
	tx.Rollback()
	return err
}

func (service *User) FindOne(cond *model.User) (*model.User, error) {
	var (
		err   error
		resut = model.User{}
	)

	if err = storage.MySqlDb().Where(cond).First(&resut).Error; err != nil {
		return nil, err
	}

	if err = storage.MySqlDb().Model(&resut).Related(&resut.Department).Related(&resut.Job).Find(&resut).Error; err != nil {
		return nil, err
	}

	return &resut, nil
}

func (service *User) FindByDepartmentId(departmentId uint) (int64, []*model.User, error) {
	var (
		err    error
		total  int64
		result = make([]*model.User, 0)
	)

	if err = storage.MySqlDb().Model(&model.User{}).Where("department_id = ?", departmentId).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Model(&model.User{}).Where("department_id = ?", departmentId).Preload("Job").Preload("Department").Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}

func (service *User) FindList() (int64, []*model.User, error) {
	var (
		err    error
		total  int64
		result = make([]*model.User, 0)
	)

	if err = storage.MySqlDb().Model(&model.User{}).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Model(&model.User{}).Preload("Job").Preload("Department").Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}